import legacy from '@vitejs/plugin-legacy';
import vue from '@vitejs/plugin-vue';
import path from 'path';
import mpaPlugin from 'vite-plugin-mpa-plus';
import { defineConfig } from 'vite';
import { loadEnv } from 'vite';
import { viteExternalsPlugin } from 'vite-plugin-externals';
import autoOptionalChainPlugin from './vite-plugins/vite-plugin-auto-optional-chain.js';
export default defineConfig((config) => {
  let pageName = '';
  let pages = {};
  let page = {};
  const plugins = [];
  const { mode, command } = config;

  const env = loadEnv(mode, './env');
  const isProd = env.NODE_ENV === 'production';
  if (command === 'build') {
    pages = require('./build/entry.config.js');
    const minimist = require('minimist');
    const outDir = minimist(process.argv.slice(2)).outDir;

    const dir = outDir?.split('/');
    console.log(dir, 'dir');

    pageName = dir.length === 3 ? dir[2] : '';
    console.log('pageName', pageName);

    plugins.push(
      viteExternalsPlugin({
        vue: 'Vue',
        pinia: 'Pinia',
        'vue-router': 'VueRouter',
      }),
    );
  } else if (command === 'serve') {
    page = require('./build/entry.config.dev.js');
  }

  return {
    root: isProd ? 'template' : process.cwd(),
    base: './',
    build: {
      emptyOutDir: true,
      outDir: './dist', // 设置打包出口的目录
      rollupOptions: {
        external: ['vue', 'vue-router'],
      },
    },
    resolve: {
      alias: {
        // 配置工程文件字符索引
        '@': path.resolve(__dirname, './src'),
        '~': path.resolve(__dirname, './src/assets'),
      },
    },
    css: {
      preprocessorOptions: {
        less: {
          additionalData: ` @import "@/assets/styles/public.less";`,
        },
      },
      postcss: {},
    },
    plugins: [
      vue(),
      // 自动为深层属性访问添加可选链操作符
      autoOptionalChainPlugin(),
      // 设置支持的浏览器版本兼容
      legacy({
        targets: ['> 1%', 'last 2 versions', 'not ie <= 8', 'iOS >= 7'],
        polyfills: [
          'es.promise',
          'es.symbol',
          'es.array.iterator',
          'es.object.assign',
          'es.promise.finally',
          'es.global-this',
        ],
        additionalLegacyPolyfills: ['regenerator-runtime/runtime'],
        modernPolyfills: ['es.global-this'],
      }),
      mpaPlugin({
        pages: pageName ? pages[pageName] : page,
      }),
      ...plugins,
    ],
    server: {
      host: '0.0.0.0',
      port: 8080,
      open: true,
      proxy: {
        // 配置接口代理
        '/api': {
          target: 'http://localhost:8085',
          rewrite: (path) => path.replace(/api/, ''),
        },
      },
      hmr: true,
    },
  };
});
